package com.qingcloud.adminbackend.controller.open;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.qingcloud.adminbackend.anno.OpenApi;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.controller.open.param.FormatCodeParam;
import com.qingcloud.adminbackend.entity.equipment.ModelDTO;
import com.qingcloud.adminbackend.entity.open.OpenEquipmentDataDTO;
import com.qingcloud.adminbackend.entity.open.OpenEquipmentDataParam;
import com.qingcloud.adminbackend.exception.WmCommonException;
import com.qingcloud.adminbackend.service.ISysFunctionService;
import com.qingcloud.adminbackend.service.ISysUserService;
import com.qingcloud.adminbackend.service.IWeatherDataService;
import com.qingcloud.adminbackend.service.impl.BaseServiceImpl;
import de.hunsicker.jalopy.Jalopy;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 开放数据API
 *
 * @author wangjinnan
 */
@RestController
@RequestMapping("/open")
public class OpenApiController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysFunctionService sysFunctionService;

    @Resource
    private BaseServiceImpl baseService;

    @Resource
    private IWeatherDataService weatherDataService;

    @ApiOperation(value = "设备分钟数据查询API", notes = "设备分钟数据查询API", response = OpenEquipmentDataDTO.class)
    @PostMapping("/equipment/minute/data")
    public AjaxResult<Object> equipmentPoolList(@RequestBody OpenEquipmentDataParam param) {
        final AjaxResult<Object> result = new AjaxResult<>();
        //检查时间段范围
        String startTime = param.getStartTime();
        String endTime = param.getEndTime();
        Long startSecond = LocalDateTime.parse(startTime, WamingConstant.NORMAL_FULL_FORMATTER)
                .toEpochSecond(ZoneOffset.of("+8"));
        Long endSecond = LocalDateTime.parse(endTime, WamingConstant.NORMAL_FULL_FORMATTER)
                .toEpochSecond(ZoneOffset.of("+8"));
        if (endSecond - startSecond > 3600) {
            result.setErroCode(500);
            result.setErroMsg("时间段范围不能超过1小时");
            return result;
        }
        result.setErroCode(2000);
        //查询授权的设备
        List<ModelDTO> equipmentList = baseService.getEquipmentIds(param.getAccessKey(),
                Collections.emptyList(), Collections.emptyList(), 0);
        if (CollUtil.isNotEmpty(equipmentList)) {
            List<String> paramEidList = Collections.emptyList();
            if (StrUtil.isNotBlank(param.getEids())) {
                paramEidList = Arrays.asList(param.getEids().split(","));
            }
            //eid参数过滤
            List<String> finalParamEidList = paramEidList;
            List<String> eids = equipmentList.stream()
                    .map(ModelDTO::getModelId)
                    .filter(it -> {
                        //参数没要求过滤
                        if (CollUtil.isEmpty(finalParamEidList)) {
                            return true;
                        }
                        return finalParamEidList.contains(it);
                    })
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(eids)) {
                List<OpenEquipmentDataDTO> equipmentData = weatherDataService.getEquipmentData(eids, startTime, endTime);
                result.setResult(equipmentData);
            } else {
                result.setResult(Collections.emptyList());
            }
        } else {
            result.setResult(Collections.emptyList());
        }
        return result;
    }

    @OpenApi
    @ApiOperation(value = "格式化java代码", notes = "格式化java代码")
    @PostMapping(value = "/format/java")
    public Map<String, String> findByIdList(@RequestBody FormatCodeParam param) {
        StringBuffer buffer = new StringBuffer(param.getSource().length());
        final Jalopy jalopy = new Jalopy();
        jalopy.setEncoding("UTF-8");
        //设置输入，第二个参数随便填
        jalopy.setInput(param.getSource(), "Hello.java");
        jalopy.setOutput(buffer);
        jalopy.format();
        //获取结果
        String result = buffer.toString();
        if (StrUtil.isBlank(result)) {
            //代码格式不正确
            throw new WmCommonException("代码不符合JAVA代码规范");
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("java", result);
        return resultMap;
    }

}
